<script setup>

import { ref, watch, onMounted } from 'vue'
import { queryPageApi ,deleteByIdsApi,addEmpApi,queryEmpByIdApi,updateByIdApi} from '@/api/emp'
import { queryAll} from '@/api/dept'
import { ElMessage } from 'element-plus'
const searchEmp = ref({
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
})



// 浅度监听
watch(() => searchEmp.value.date, (newValue, oldValue) => {
    console.log('监听执行了')
    if (newValue.length == 2) {
        searchEmp.value.begin = newValue[0]
        searchEmp.value.end = newValue[1]

    } else {
        searchEmp.value.begin = ''
        searchEmp.value.end = ''
    }
})


const empList = ref([]);
const handleSearch = () => {
    console.log('Search:', searchEmp.value)
}
const handleReset = () => {

    searchEmp.value = {
        name: '',
        gender: '',
        date: []
    }
    handleSearch()
}
// 定义分页数据
// 当前页是1
const currentPage = ref(1)
// 每页显示10条数据
const pageSize = ref(10)
// 总条数  默认0 
const total = ref(0)
// 设置组件的尺寸规格
const size = 'default'
// 是否禁用
const disabled = false



// 分页处理
// 参数 val：表示用户切换到的 “当前页码”（例如 2、3 等）。
// 分页每页大小发生改变
const handleSizeChange = (val) => {
    // 从第一页开始
    currentPage.value = 1
    //  (前往第几页的框)每页显示val条数据
    pageSize.value = val
    //   搜索
    searchHandler()



}
// (用户直接点击第几页)当前页发生变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    searchHandler()
}

// 执行分页搜索
const searchHandler = async () => {
    let result = await queryPageApi(currentPage.value, pageSize.value, searchEmp.value.name, searchEmp.value.gender, searchEmp.value.begin, searchEmp.value.end)
    // 将数据存到List集合(接口看的)
    empList.value = result.data.rows
    // 分页数据完善(接口看的)
    total.value = result.data.total

}













// 新增或修改弹框
const dialogshow = ref(false)

// 展示弹框
const showDialog = () => {
    dialogshow.value = true
    // 弹框标题设置
    Tips.value = "新增员工"
}

// 定义表单对象,接收新增数据
const formData = ref({
    image: "",
    username: "",
    name: "",
    gender: "",
    job: " ",
    entryDate: "",
    deptId: "",
    phone: "",
    salary: 0,
    exprList: []
})

const Tips = ref("新增员工")

// 定义下拉框数据
// 性别数据
const genderList = ref([
    { id: "1", name: "男" },
    { id: "2", name: "女" }
])

// 职位数据
const jobList = ref([
    { id: "1", name: "讲师" },
    { id: "2", name: "班主任" },
    { id: "3", name: "就业指导" },
    { id: "4", name: "其他" }
])

// 部门数据
const deptList = ref([])
const loadAllDept = async () => {
    let result = await queryAll()
    deptList.value = result.data
}

// 文件上传

//预览图片地址：imageUrl
// const imageUrl = ref(null)
// //文件上传成功，调用的方法：handleAvatarSuccess

//文件上传前调用的方法：beforeAvatarUpload



const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    // 将预览图片换成响应的图片
    formData.value.image = response.data
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片必须是jpg格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片最大是2mb')
        return false
    }
    return true
}

// 新增工作经历
const addWork = () => {
    formData.value.exprList.push({

        "begin": "",
        "end": "",
        "company": "",
        "job": ""


    })

}

// 删除工作经历，根据索引将empForm.exprList指定的数据删除
// splice() 方法的第一个参数是开始修改的索引位置，第二个参数是要删除的元素个数
const deleteWork=(index)=>{
  formData.value.exprList.splice(index,1)
}





watch(formData ,(newValue, oldValue) => {
   formData.value.exprList.forEach((item,index)=>{ 
if(item.date){
   formData.value.exprList[index].begin=item.date[0]
    formData.value.exprList[index].end=item.date[1]
}
   
})
},{deep:true})


// 创建函数，在函数中调用api的方法，实现数据保存
//·表单校验
//·关联表单·ref
// 校验规则rulesblur(鼠标离开事件)
// 点击确认，进行表单校验

const ruleFormRef=ref(null)

// 验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

// 添加 修改

const addEmkp=async()=>{ 


    if (!ruleFormRef) return
   await ruleFormRef.value.validate(async(valid,fields) => {
        if (valid) {
            let result = null

            if(formData.value.id){ 
                // 修改
                result = await updateByIdApi(formData.value)
            }else{ 
                // 添加
                 result = await addEmpApi(formData.value)
            }
            
            // 远程调用
            
            if (result.code) {
                // 提示信息
                ElMessage.success("操作成功")
                dialogshow.value = false


            } else {
                ElMessage.error("操作失败")
            }
        } else {
           
        }
    })



}






// 修改回显

// 在api创建根据id查询员工信息


// // 根据ID查询员工信息
const queryEmpById = async (id) => {
    let result = await queryEmpByIdApi(id)
    formData.value = result.data



    // 对exprList遍历 取出 date[]的bengin和end
    formData.value.exprList.forEach((item,index)=>{
        item.date=[]
        item.date.push(item.begin)
        item.date.push(item.end)


    })

    dialogshow.value = true

}






onMounted(() => {
    // 获取所有部门信息
    searchHandler()
    loadAllDept()
})


// 单条数据删除

const deleteById=(id)=>{ 

deleteIds.value=[id]

deleteByIds()

}



// 批量删除

const deleteIds=ref([])
// 处理所有选中的行信息 
const handleSelectionChange= (selection)=>{ 
    console.log(selection)

    let idCollections= selection.map(function (item) {
        return item.id


    })
     deleteIds.value= idCollections

}

// 删除操作
const deleteByIds=async()=>{ 
let result=await deleteByIdsApi(deleteIds.value)

// 加载最新数据
searchHandler()
}




</script>

<template>
    <h1>员工管理</h1> <br>
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchEmp">
        <el-form-item label="姓名">
            <el-input v-model="searchEmp.name" placeholder="请输入员工姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别">
            <el-select v-model="searchEmp.gender" placeholder="请选择">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="入职日期">
            <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="searchHandler">查询</el-button>
            <el-button @click="handleReset">清空</el-button>
        </el-form-item>
    </el-form>
    <el-button type="primary" @click="dialogshow = showDialog"> 新增员工</el-button>
    <el-button type="warning" @click="deleteByIds"> - 批量删除</el-button>
    <br><br>
    <!-- 新增或修改的弹框 -->
    <el-dialog v-model="dialogshow" :title="Tips" width="800" :before-close="handleClose">




        <el-form ref="ruleFormRef"  style="max-width: 800px" :model="formData" :rules="rules" label-width="auto">

            <el-row :gutter="0">
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name"><el-input v-model="formData.name" />
                    </el-form-item>
                </el-col>


                <el-col :span="12">
                    <el-form-item label="账号" prop="username"> <el-input v-model="formData.username" />

                    </el-form-item>

                </el-col>
            </el-row>

            <el-row :gutter="0">
                <el-col :span="12">
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="formData.gender" placeholder="请选择性别">
                            <el-option v-for="(gen, index) in genderList" :key="index" :label="gen.name"
                                :value="gen.id" />

                        </el-select>
                    </el-form-item>
                </el-col>


                <el-col :span="12">
                    <el-form-item label="职位" prop="job">
                        <el-select v-model="formData.job" placeholder="请选择职位">
                            <el-option v-for="(job, index) in jobList" :key="index" :label="job.name" :value="job.id" />


                        </el-select>
                    </el-form-item>

                </el-col>
            </el-row>


            <el-row :gutter="0">
                <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="formData.phone" />
                    </el-form-item>

                </el-col>


                <el-col :span="12">
                    <el-form-item label="薪资" prop="salary">
                        <el-input v-model="formData.salary" />
                    </el-form-item>

                </el-col>
            </el-row>



            <el-row :gutter="0">
                <el-col :span="12">

                    <el-form-item label="入职时间" required>
                        <el-col :span="10">
                            <el-form-item prop="entryDate">
                                <el-date-picker v-model="formData.entryDate" type="date" aria-label="Pick a date"
                                    placeholder="请选择入职时间" style="width: 100%" />
                            </el-form-item>
                        </el-col>


                    </el-form-item>

                </el-col>


                <el-col :span="12">
                    <el-form-item label="部门" prop="deptId">
                        <el-select v-model="formData.deptId" placeholder="请选择部门" style="width: 100%">
                            <el-option v-for="(dept, index) in deptList" :key="index" :label="dept.name"
                                :value="dept.id" />
                        </el-select>
                    </el-form-item>
                </el-col>





                <el-col :span="24">
                    <el-form-item label="头像" prop="image">
                        <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="formData.image" :src="formData.image" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>

                    </el-form-item>
                </el-col>


                <el-col :span="24">





                    <el-form-item label="工作经历">
                        <el-button type="success" @click="addWork">新增工作经历</el-button>

                    </el-form-item>


                    <el-row  v-for="(exp, index) in formData.exprList" :key="index"  >
                        <el-col :span="10">

                              <el-form-item prop="exprList.date" label="入职时间" label-width="80px">
              <el-date-picker type="daterange" v-model="exp.date" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
            </el-form-item>


                            
                   

                             
                        </el-col>

                        <el-col :span="6">
                              <el-form-item label="公司名字" prop="salary">
                        <el-input v-model="exp.company" />
                    </el-form-item>


                             
                        </el-col>

                        <el-col :span="6">

                            <el-form-item label="职位" prop="salary">
                        <el-input v-model="exp.job" />
                    </el-form-item>


                             
                        </el-col>

                        <el-col :span="2">

                     <el-button type="danger" @click="deleteWork(index)">删除</el-button>


                             
                        </el-col>





                    </el-row>
                      </el-col>
            </el-row>










            <el-form-item>
                <el-button @click=>取消</el-button>
                <el-button type="primary" @click=" ">
                    重置
                </el-button>
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogshow = false">取消</el-button>
                <el-button type="primary" @click=" addEmkp" >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>


    <!-- 表格 -->
    <el-table :data="empList"   @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="主键ID" width="180" />
        <el-table-column prop="name" label="名字" width="180" />
        <el-table-column prop="gender" label="性别">
            <template #default="scope">
                <el-tag v-if="scope.row.gender == 1">男</el-tag>
                <el-tag v-else>女</el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="image" label="图像">
            <!-- 接收从父组件传递过来的作用域数据，通常是一个包含当前行信息的对象 -->
            <template #default="scope">
                <el-image :src="scope.row.image" style="width: 100px; height: 100px;" />
            </template>
        </el-table-column>


        <el-table-column prop="job" label="职位">
            <template #default="scope">
                <el-tag v-if="scope.row.job == 1">讲师</el-tag>
                <el-tag v-else-if="scope.row.job == 2">班主任</el-tag>
                <el-tag v-else-if="scope.row.job == 3">咨询师</el-tag>
                <el-tag v-else>其他</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="salary" label="月薪" width="180" />
        <el-table-column prop="entryDate" label="入职时间" width="180" />
        <el-table-column prop="deptName" label="部门名称" width="180" />
        <el-table-column fixed="right" label="Operations" width="120">
            <template #default = "scope">
                <el-button link size="small" type="primary" @click="queryEmpById(scope.row.id)">编辑</el-button>
                <el-button link size="small" type="primary" @click="deleteById(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>

    </el-table>


    <br>
    <!-- 当前页数 -->
    <!-- 每页多少条 -->
    <!-- total总条数 -->
    <!-- 分页 -->
    <div class="pdbox">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    </div>
    <!-- 把部门信息动态展示再进行渲染,定义成变量,然后循环输出-->


</template>

<style scoped>
.pdbox {
    margin-top: 15px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>